package com.gx.components
{
	import com.gx.data.IXMLDecoder;
	import com.gx.interfaces.IComponent;
	import com.gx.interfaces.ILoader;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;

	public class BitmapLoader extends Bitmap implements IXMLDecoder, IComponent, ILoader
	{
		private var loader:Loader;
		public var url:String="";
		public var id:String = "";
		
		public function BitmapLoader(bitmapData:BitmapData=null, pixelSnapping:String="auto", smoothing:Boolean=false)
		{
			super(bitmapData, pixelSnapping, smoothing);
		}
		
		public function decode(bitmapXML:XML):void
		{
			/*
				<util:BitmapLoader id="[string]" url="[string]" />
			*/
			this.url = bitmapXML.@url;
			this.id = bitmapXML.@id;
		}
		
		public function load(bitmapUrl:String=null):void
		{
			if(bitmapUrl != null)
			{
				url = bitmapUrl;
			}
			loader = new Loader();
	        loader.contentLoaderInfo.addEventListener(Event.COMPLETE, bitmapLoadComplete);
	        loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, bitmapLoadError);
	
	        var request:URLRequest = new URLRequest(url);
	        loader.load(request);
		}
		
		public function bitmapLoadComplete(event:Event):void
		{
			this.bitmapData = loader.content as BitmapData
			this.dispatchEvent(event);
		}
		
		public function bitmapLoadError(e:IOErrorEvent):void
		{
			this.dispatchEvent(e);
		}
		
		private var _id:int;
		public function get id():int {return _id;}
		public function set id(value:int):void {_id = value;}
		
		private var _parent:IComponent;
		public function get parent():IComponent {return _parent;}
		public function set parent(value:IComponent):void {_parent = value;}
		
		public function init():void
		{
			
		}
		
		private var _components:Array = new Array();
		public function get components():Array {return _components;}
		public function set components(value:Array):void 
		{
			for each(var c:Component in value)
			{
				addComponent(c);
			}
		}
		
		public function addComponent(c:Component):void
		{
			_components.push(c);
			c.parent = this;
		}
		
	}
}